package com.honey.mybatis.generator.dao.method;

import java.util.List;

import com.honey.compilation.java.AbstractJavaCompilation;
import com.honey.compilation.java.IfBlock;
import com.honey.compilation.java.Method;
import com.honey.compilation.java.Parameter;
import com.honey.core.dbmapping.introspect.IntrospectSchema;
import com.honey.core.dbmapping.introspect.IntrospectSchemaColumn;
import com.honey.core.dbmapping.introspect.IntrospectTableColumn;
import com.honey.core.dbmapping.structure.TableColumn;
import com.honey.core.types.FullyQualifiedJavaType;
import com.honey.core.utils.EmptyUtility;
import com.honey.mybatis.generator.MybatisPlugin;
import com.honey.mybatis.generator.dao.DaoConstant;

/**
 * 按照primaryKey查询
 * @author Administrator
 *
 */
public class SelectByPrimaryKeyMethod extends AbstractCreateInterfaceMethod{

	private static final String METHOD_NAME="selectByPrimaryKey";

	private boolean isUseSession = false ;
	
	public SelectByPrimaryKeyMethod(
			AbstractJavaCompilation clazz, MybatisPlugin belongPlugin,
			IntrospectSchema introspectSchema,
			IntrospectSchemaColumn introspectSchemaColumn
			) {
		super(clazz, belongPlugin, introspectSchema, introspectSchemaColumn);
	}
	
	public SelectByPrimaryKeyMethod(
			AbstractJavaCompilation clazz, MybatisPlugin belongPlugin,
			IntrospectSchema introspectSchema,
			IntrospectSchemaColumn introspectSchemaColumn,
			boolean  isUseSession
			) {
		super(clazz, belongPlugin, introspectSchema, introspectSchemaColumn);
		this.isUseSession = isUseSession;
	}
	
	/* (non-Javadoc)
	 * @see com.honey.mybatis.generator.AbstractMethod#addBody(com.honey.compilation.java.Method)
	 */
	@Override
	protected void addBody(Method method) {	
		IfBlock ifBlock = null;
		if( isUseSession()){
			ifBlock = new IfBlock(new StringBuilder().append( DaoConstant.SQL_SESSION_NAME ).append(" == null").toString());
			ifBlock.addBodyLine("return null");
			method.addBlocks(ifBlock);
		}
		
		List<TableColumn> columns =  ((IntrospectTableColumn)introspectSchemaColumn).primaryKeyColumns();
		if( columns.size() == 1){
			method.addBodyLine(
					new StringBuilder( )
					.append("return (")
					.append(method.getReturnType().getFullName())
					.append(")")
					.append(mybatisPlugin.getDependentModel().call(null))
					.append("selectOne( ")
					.append( isUseSession?DaoConstant.SQL_SESSION_NAME+" , ":"" )
					//.append(DaoConstant.SELECT_BY_PRIMARYKEY_FIELD_NAME)
					.append( super.getMapperId().getSelectByPrimaryKeyMapperId() )
					.append(" , ")
					.append(columns.get(0).getJavaProperty())
					.append(" )")
					.toString()
			);
		}else if( columns.size() > 1){
			method.addBodyLine("Map<String, Object> parameter = new HashMap<String, Object>();");
			for( TableColumn tc : columns ){
				method.addBodyLine("parameter.put(\""+tc.getJavaProperty()+"\","+tc.getJavaProperty()+")");
			}
			method.addBodyLine(
					new StringBuilder( )
					.append("return (")
					.append(method.getReturnType().getFullName())
					.append(")")
					.append(mybatisPlugin.getDependentModel().call(null))
					.append("selectOne( ")
					.append( isUseSession()?DaoConstant.SQL_SESSION_NAME+" , ":"" )
					//.append(DaoConstant.SELECT_BY_PRIMARYKEY_FIELD_NAME)
					.append( super.getMapperId().getSelectByPrimaryKeyMapperId() )
					.append(" , parameter )")
					.toString()
			);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see com.honey.mybatis.generator.AbstractMethod#getMethodName()
	 */
	@Override
	protected String getMethodName() {		
		String answer = null;
		if( !isUseSession ){
			answer = METHOD_NAME;
		}else if( isUseSession  && mybatisPlugin.isEnableUseSqlSession() ){
			answer = METHOD_NAME;
		}
		return answer;
	}

	/**
	 * @return the isUseSession
	 */
	@Override
	public final boolean isUseSession() {
		return isUseSession;
	}

	/* (non-Javadoc)
	 * @see com.honey.mybatis.generator.AbstractMethod#getJavaDoc()
	 */
	@Override
	protected String[] getJavaDoc() {
		String[] answer = new String[]{
			"按照主键查询一条记录。"
		};
		return answer;
	}

	/* (non-Javadoc)
	 * @see com.honey.mybatis.generator.AbstractMethod#getReturnType()
	 */
	@Override
	protected FullyQualifiedJavaType getReturnType() {
		
		return super.getEntityClassType(introspectSchema.getSchema());
	}
	
	protected Parameter[] getParameter() {
		List<TableColumn> primaryKeyColumns = ((IntrospectTableColumn)introspectSchemaColumn).primaryKeyColumns() ;
		int size = 1;
		if( ! EmptyUtility.isListEmpty(primaryKeyColumns)){
			size +=primaryKeyColumns.size();
		}
		
		Parameter[] answer = new Parameter[size];
		Parameter parameter = null;
		if( isUseSession()){
			parameter = new Parameter(DaoConstant.SQL_SESSION_PACKAGE,DaoConstant.SQL_SESSION_NAME);
			parameter.addJavaDocLine("外部传入SqlSession");
			answer[0] = parameter;
		}
		TableColumn tc = null;
		for( int i=0 , length = primaryKeyColumns.size();i < length ; i++ ){
			tc = primaryKeyColumns.get(i); 
			parameter = new Parameter(tc.getFullyQualifiedJavaType(),tc.getJavaProperty());
			setBaseType(parameter);
			parameter.addJavaDocLine(tc.getComment());
			answer[i+1] = parameter;
		}
		return answer ;
	}
	
	
//	
//	private static final String SQL_SESSION_PACKAGE="org.apache.ibatis.session.SqlSession";
//	
//	private static final String SQL_SESSION_NAME="session";
//	
//	public List<Method> createMethod(IntrospectSchema introspectSchema, IntrospectSchemaColumn introspectSchemaColumn) {
//		Schema schema = introspectSchema.getSchema();
//		List<Method> answer = new ArrayList<Method>();
//		if( schema instanceof Table ){
//			Table table = (Table)schema ;
//			List<TableColumn> columns= ((IntrospectTableColumn)introspectSchemaColumn).primaryKeyColumns();
//			answer.add(createSelectMethod(table,columns,false));
//			if (mybatisPlugin.isInterfaceUseSqlSession()){
//				answer.add(createSelectMethod(table,columns,true));
//			}
//		}
//		return answer;
//	}
//	
//	/**
//	 * 创建查询方法 
//	 * @param schema
//	 * @return
//	 */
//	private Method createSelectMethod(Table table,List<TableColumn> columns,boolean useSqlSession) {
//		Method answer = new Method(METHOD_NAME,super.getEntityClassType(table ));
//		Parameter parameter = null;
//		for( TableColumn tc : columns ){
//			if( useSqlSession){
//				parameter = new Parameter(new FullyQualifiedJavaType(SQL_SESSION_PACKAGE),SQL_SESSION_NAME);
//				parameter.addJavaDocLine("外部传入SqlSession");
//				answer.addParameter(parameter);
//			}
//			parameter = new Parameter(tc.getFullyQualifiedJavaType(),tc.getJavaProperty());
//			setBaseType(parameter);
//			parameter.addJavaDocLine(tc.getComment());
//			answer.addParameter(parameter);
//		}
//		answer.addJavaDocLine("按照主键查询记录");
//		return answer;
//	}
	
	
}
